package com.sl.au.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.sl.au.entity.Account;
import com.sl.au.entity.ArchiveInfo;
import com.sl.au.entity.EventRegister;
import com.sl.au.entity.EventRegisterAndTaskView;
import com.sl.au.entity.EventRegisterTask;
import com.sl.au.entity.EventReport;
import com.sl.au.entity.Grading;
import com.sl.au.entity.GridAreaInfo;
import com.sl.au.entity.EventTask;
import com.sl.au.entity.Option;
import com.sl.au.entity.PartBaseInfo;
import com.sl.au.entity.UserSingle;
import com.sl.au.entity.VisitorReward;
import com.sl.au.entity.User;
import com.sl.au.entity.EventToEvaluateUser;
import com.sl.au.entity.EventType;
import com.sl.au.service.EventReportService;
import com.sl.au.service.EventTypeService;
import com.sl.au.service.AccountService;
import com.sl.au.service.ArchiveInfoService;
import com.sl.au.service.EventRegisterService;
import com.sl.au.service.UserService;
import com.sl.au.service.VisitorRewardService;
import com.sl.au.service.OptionService;
import com.sl.au.service.PartBaseInfoService;
import com.sl.au.service.GradingService;
import com.sl.au.service.GridAreaInfoService;
import com.sl.au.service.IdentifyService;
import com.sl.au.service.OperateLogService;
import com.sl.au.service.GridUserDetailsService;
import com.sl.au.service.EventToEvaluateUserService;
import com.sl.utils.ExdeUtil;
import com.sl.utils.MsgHelper;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping(value = "/ui/eventRegister")
public class EventRegisterController extends BaseController {

	@Autowired
	EventReportService eventReportService;
	@Autowired
	EventRegisterService eventRegisterService;
	@Autowired
	GradingService gradingService;
	@Autowired
	GridUserDetailsService gridUserDetailsService;
	@Autowired
	OptionService optionService;
	@Autowired
	UserService userService;
	@Autowired
	GridAreaInfoService gridAreaInfoService;
	@Autowired
	IdentifyService identifyService;
	@Autowired
	PartBaseInfoService partBaseInfoService;
	@Autowired
	ArchiveInfoService archiveInfoService;
	@Autowired
	AccountService accountService;
	@Autowired
	VisitorRewardService visitorRewardService;
	@Autowired
	EventTypeService eventTypeService;
	@Autowired
	OperateLogService operateLogService;
	@Autowired
	EventToEvaluateUserService eventToEvaluateUserService;
	/**
	 * 初始化页面
	 * 
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(ModelAndView modelAndView) {

		String device = request.getParameter("device");
		String eventRegister = request.getParameter("eventRegisterIdentify");
		String eventReport = request.getParameter("eventReportIdentify");
		
		// 移动端
		if (StringUtils.hasText(device) && this.DEVICE.equals(device)) {
			// 移动端访问的首页
			modelAndView.setViewName("mobile/event/mobileEventRegister");
		} else {
			// PC端
			if (StringUtils.hasText(eventRegister) || StringUtils.hasText(eventReport)||eventReport!=null) {
				modelAndView = createLayoutView("eventRegister/eventRegisterEdit");
				List<Grading> gradings= null;//= this.gradingService.getRepository().getBindingGrading();
				if(StringUtils.hasText(eventRegister)){
					EventRegister temp =this.eventRegisterService.getRepository().findOne(eventRegister);
					if(temp.getRegisterEventToNetGrid()!=null){
						gradings =this.gridUserDetailsService.getRepository().getGradingByGrid(temp.getRegisterEventToNetGrid().getId());
					}
				}else if(StringUtils.hasText(eventReport)){
					EventReport temp =this.eventReportService.getRepository().findOne(eventReport);
					if(temp.getReportEventToNetGrid()!=null){
						gradings =this.gridUserDetailsService.getRepository().getGradingByGrid(temp.getReportEventToNetGrid().getId());
					}
				}else{
				}
				if(gradings!=null&&gradings.size()>0){
					gradings.sort((Grading g1, Grading g2) -> g1.getGradingLevel().getExtended1().compareTo(g2.getGradingLevel().getExtended1()));	
				}
				List<Option> registerEventSeriousLevels = this.optionService.getRepository().findByGroup("事件严重等级");
				modelAndView.addObject("eventRegisterIdentify", eventRegister);
				modelAndView.addObject("eventReportIdentify", eventReport);
				modelAndView.addObject("gradings", gradings);
				modelAndView.addObject("registerEventSeriousLevels", registerEventSeriousLevels);
			} else {
				eventReport =request.getParameter("eventReportId");
				modelAndView = createLayoutView("eventRegister/eventRegister");
				
				List<Option> options = this.optionService.getRepository().findByGroup("内部事件流转状态");
				modelAndView.addObject("options", options);
				modelAndView.addObject("eventReportIdentify", eventReport);
				
				Option limitOpt = optionService.getRepository().findByGroupAndTitle("超时时限", "处理中").get(0);
				String dealLimit = "0.5";//默认时限
				if(limitOpt != null) {
					dealLimit = limitOpt.getValue();
				}
				modelAndView.addObject("dealLimit", dealLimit);
			}
		}
		return modelAndView;
	}
	
	@RequestMapping(value = "getpage", method = RequestMethod.GET)
	public Map<String, Object> getpage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		String type=request.getParameter("type");
		String eventReportIdentify= request.getParameter("eventReportIdentify");
		List<EventRegisterTask> rvs2 = null;
		List<EventRegisterAndTaskView> rvs = null;
		
		String roleId = this.getMyAccount().getRole().getId();
		int count=0;
		if (StringUtils.hasText(eventReportIdentify)){
			//eventRegister= this.eventRegisterService.getPageByEventReportAndType(start, length,eventReportIdentify, key, type, "createTime", Sort.Direction.DESC);
			//count = this.eventRegisterService.getCountByEventReportAndType(eventReportIdentify,key,type);
//			rvs=eventRegisterService.findPageByReportAndType(start,length,eventReportIdentify,key,type,"createTime", Sort.Direction.DESC);
			rvs2=eventRegisterService.findPageByReportAndType3(start,length, roleId,eventReportIdentify,key,type,"createTime", Sort.Direction.DESC);
			count=eventRegisterService.findCountByReportAndType3(roleId,eventReportIdentify,key,type);
		}else{
			//eventRegister= this.eventRegisterService.getPageAndType(start, length, key, type, "createTime", Sort.Direction.DESC);
			//count = this.eventRegisterService.getCountAndType(key, type);
//			rvs=eventRegisterService.findPageAndType(start, length, key, type, "createTime", Sort.Direction.DESC);
			rvs2=eventRegisterService.findPageAndType3(start, length, roleId, key, type, "createTime", Sort.Direction.DESC);
			count=eventRegisterService.findCountAndType3(roleId, key, type);
		}
		 
		map.put("data", rvs2);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	@RequestMapping(value = "getpageForSelfInit", method = RequestMethod.GET)
	public Map<String, Object> getpageForSelfInit(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		
		String state ="";
		List<Option> options=this.optionService.getRepository().findByGroupAndTitle("内部事件流转状态", "初始化");
		if(options.size()>0){
			state=options.get(0).getId();
		}
		List<EventRegister> eventRegister=this.eventRegisterService.getPageByStateAndUser(start, length, state, this.getMyAccount().getUser().getId(), key, "createTime", null);
		int count=this.eventRegisterService.getCountByStateAndUser(state, this.getMyAccount().getUser().getId(), key);
		 
		map.put("data", eventRegister);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	@RequestMapping(value = "getpageForSelfReject", method = RequestMethod.GET)
	public Map<String, Object> getpageForSelfReject(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		
		String state ="";
		List<Option> options=this.optionService.getRepository().findByGroupAndTitle("内部事件流转状态", "已退回");
		if(options.size()>0){
			state=options.get(0).getId();
		}
		List<EventRegister> eventRegister=this.eventRegisterService.getPageByStateAndUser(start, length, state, this.getMyAccount().getUser().getId(), key, "createTime", null);
		int count=this.eventRegisterService.getCountByStateAndUser(state, this.getMyAccount().getUser().getId(), key);
		 
		map.put("data", eventRegister);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	@RequestMapping(value = "getDetailInfo", method = RequestMethod.GET)
	public MsgHelper getDetailInfo() {
		String eventRegister = request.getParameter("eventRegisterIdentify");
		String eventReport = request.getParameter("eventReportIdentify");
		
		List<Option> state =this.optionService.getRepository().findByGroupAndTitle("内部事件流转状态", "初始化");
		MsgHelper helper =new MsgHelper();
		
		if(state.size()>0){
			helper.put("state", state.get(0));
		}
			
		if (StringUtils.hasText(eventReport) && !eventReport.equals("")) {
			if (StringUtils.hasText(eventRegister) && !eventRegister.equals("")) {
				EventRegister register = this.eventRegisterService.getRepository().findOne(eventRegister);
				if (register.getRegisterEventToReportEvent().getId().equals(eventReport)) {
					helper.put("eventRegister", register);
					helper.put("eventToEvaluateUser",this.eventRegisterService.getEventToEvaluateUserRepository().findListByEventRegister(register.getId()));
					return helper;
				} else {
					return MsgHelper.failed();
				}
			} else {
				helper.put("eventReport",
						this.eventReportService.getRepository().findOne(eventReport));
				return helper;
			}
		} else {
			if (StringUtils.hasText(eventRegister) && !eventRegister.equals("")) {
				EventRegister register = this.eventRegisterService.getRepository().findOne(eventRegister);
				helper.put("eventRegister", register);
				helper.put("eventToEvaluateUser",this.eventRegisterService.getEventToEvaluateUserRepository().findListByEventRegister(register.getId()));
				return helper;
			} else {
				return MsgHelper.failed();
			}
		}
	}
	@RequestMapping(value = "getValuateLevelUserDetail", method = RequestMethod.GET)
	public MsgHelper getValuateLevelUserDetail() {
		String evaluateLevel = request.getParameter("evaluateLevel");
		String eventType =request.getParameter("eventType");
		String grid =request.getParameter("grid");
		String eventRegisterIdentify =request.getParameter("eventRegisterIdentify");
		if(eventRegisterIdentify==null||eventRegisterIdentify.isEmpty()){
			List<List<UserSingle>> users=this.eventRegisterService.findUserSingle(evaluateLevel, eventType, grid);
			return MsgHelper.success().put("list", users);
		}
		else
		{
			List<List<UserSingle>> users=this.eventRegisterService.findUserSingleByIdentify(eventRegisterIdentify);
			return MsgHelper.success().put("list", users);
		}
	}
	@RequestMapping(value = "/saveReportAndRegisterEvent", method = RequestMethod.POST)
	public Map<String, Object> saveReportAndRegisterEvent(MultipartHttpServletRequest requests) {
		MultipartFile file = requests.getFile("file");
		Map<String, Object> map = new HashMap<String, Object>();
		int code = -1;
		boolean isMessageToReport =true;
		EventReport eventReport =this.eventReportService.getRepository().findOne(request.getParameter("eventReport"));
		
		JSONObject project = JSONObject.fromObject(request.getParameter("eventRegister"));
		EventRegister eventRegister = (EventRegister) JSONObject.toBean(project, EventRegister.class);
		
		String dateTime = request.getParameter("accTime");
		//Date registerEventReportTime=Date.valueOf(request.getParameter("accTime"));
		java.util.Date registerEventReportTime= ExdeUtil.str2Date(dateTime, "yyyy-MM-dd HH:mm:ss");
		eventRegister.setRegisterEventReportTime(registerEventReportTime);
		// 获取当前EventReport图片的存储路径
				String url = "";
				if (file != null && !file.isEmpty()) {
					// 注意路径的构建
					url = getUploadFilePath(this.fileUploadPath, "img/eventRegister", file);
					eventRegister.setRegisterEventImgAdress(url);
				}
		
		EventRegister eventRegisterTemp =this.eventRegisterService.getRepository().findOne(eventRegister.getId());
		
		//新增或者修改的判断
		if(eventRegisterTemp!=null){
			if(eventReport.getId()!=eventRegisterTemp.getRegisterEventToReportEvent().getId())
			{
				map.put("code", code);
				return map;
			}
		}
		
        EventTask registerTask =null;
		
		String registerState =request.getParameter("registerState");
		String registerTaskMemo=request.getParameter("registerTaskMemo");
		if(!registerState.isEmpty()){
			
			List<Option> o=this.optionService.getRepository().findByGroupAndTitle("内部事件流转状态", registerState);			
			if(o.size()>0){
				eventRegister.setRegisterEventState(o.get(0));
			}
			if(registerState.equals("初始化")||registerState.equals("已分配")){
				//获取事件所属网格,看是否还需要
				GridAreaInfo info= this.gridAreaInfoService.GetGridAreaInfoByCoordinate(eventRegister.getLongitude(), eventRegister.getLatitude());
				eventRegister.setRegisterEventToNetGrid(info);
			}
			//获取事件编码
			String areaId ="";
			if(eventRegister.getRegisterEventToNetGrid()!=null&&eventRegister.getRegisterEventToNetGrid().getDivision()!=null){
				areaId=eventRegister.getRegisterEventToNetGrid().getDivision().getId();
			}
			String eventTypeId="";
			if(eventRegister.getRegisterEventType()!=null){
				eventTypeId=eventRegister.getRegisterEventType().getId();
			}
			String registerEventIdentify=this.identifyService.getEventIdentifyByGridAndEventType(areaId, eventTypeId);
			eventRegister.setRegisterEventIdentify(registerEventIdentify);
			
			if(registerState.equals("初始化")||eventRegisterTemp==null){
				eventRegister.setRegisterEventCreateUser(this.getMyAccount().getUser());
				eventRegister.setRegisterEventAccTime(DateTime.now().toDate());
			}else if(eventRegisterTemp!=null){
				eventRegister.setRegisterEventCreateUser(eventRegisterTemp.getRegisterEventCreateUser());
				eventRegister.setRegisterEventAccTime(eventRegisterTemp.getRegisterEventAccTime());
			}
			if(!(eventRegisterTemp!=null&&eventRegisterTemp.getRegisterEventState().getId().equals(eventRegister.getRegisterEventState().getId()))){
				registerTask=new EventTask();
				registerTask.setEventId(eventRegister.getId());
				registerTask.setEventTaskState(o.get(0));
				registerTask.setEventTaskTime(DateTime.now().toDate());
				registerTask.setEventTaskUser(this.getMyAccount().getUser());
				registerTask.setEventTaskMemo(registerTaskMemo);
				registerTask.setEventTaskOperate("初始化内部事件");
			}
		}
		else{
			map.put("code", code);
			return map;
		}
		//内部默认创建事件源
		if(eventReport==null){
			eventReport=new EventReport();
			eventReport.setLatitude(eventRegister.getLatitude());
			eventReport.setLongitude(eventRegister.getLongitude());
			eventReport.setReportAccTime(eventRegister.getRegisterEventReportTime());
			eventReport.setReportAdress(eventRegister.getRegisterEventAdress());
			eventReport.setReportContent(eventRegister.getRegisterEventContent());
			//标注事件来源
			Option org=this.optionService.getRepository().findByGroupAndExtended1("事件上报来源", "中心上报");
			if(org!=null){
				eventReport.setReportEventOrg(org);
			}
			//------------
			
			List<Option> option=this.optionService.getRepository().findByGroupAndTitle("事件上报属性状态", "真实有效");
			if(option.size()>0){
				eventReport.setReportEventAttrVariable(option.get(0));
			}
			option=this.optionService.getRepository().findByGroupAndTitle("事件上报状态", "初始化");
			if(option.size()>0){
				eventReport.setReportEventVariable(option.get(0));
			}
			eventReport.setReportEventToNetGrid(eventRegister.getRegisterEventToNetGrid());
			eventReport.setReportEventType(eventRegister.getRegisterEventType());
			eventReport.setRealReportEventType(eventRegister.getRegisterEventType());
			eventReport.setReportImgAdress(eventRegister.getRegisterEventImgAdress());
			eventReport.setReportMemo(eventRegister.getRegisterEventMemo());
			eventReport.setReportUser(eventRegister.getRegisterEventCreateUser());
			isMessageToReport =false;
		}
		
		//设置内部事件的事件源
		eventRegister.setRegisterEventToReportEvent(eventReport);
		
		//变更事件源状态
		EventTask reportTask =null;
		
		if(!eventReport.getReportEventVariable().getTitle().equals("已受理")){
			List<Option> or=this.optionService.getRepository().findByGroupAndTitle("事件上报状态", "已受理");
			if(or.size()>0){
				eventReport.setReportEventVariable(or.get(0));
			}
			
			reportTask =new EventTask();
			reportTask.setEventId(eventReport.getId());
			reportTask.setEventTaskState(or.get(0));
			reportTask.setEventTaskTime(DateTime.now().toDate());
			reportTask.setEventTaskUser(this.getMyAccount().getUser());
			reportTask.setEventTaskOperate("受理事件源");
		}else{
			isMessageToReport=false;
		}
		List<EventToEvaluateUser> dlist = new ArrayList<>();

		JSONArray eventToEvaluateUserList = JSONArray.fromObject(request.getParameter("eventToEvaluate"));
		for (int i = 0; i < eventToEvaluateUserList.size(); i++) {
			JSONObject jsonObject = eventToEvaluateUserList.getJSONObject(i);
			EventToEvaluateUser eventToEvaluateUser = (EventToEvaluateUser) JSONObject.toBean(jsonObject,
					EventToEvaluateUser.class);
			BigDecimal b = new  BigDecimal(eventToEvaluateUser.getScale());  
			double f = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
			eventToEvaluateUser.setScale(f);
			//设置扣分登记人员信息
			eventToEvaluateUser.setRegisterEvent(eventRegister);
			dlist.add(eventToEvaluateUser);
		}
		this.eventRegisterService.saveAll(eventRegister,registerTask,dlist,eventReport,reportTask);
		//判断是否是游客上报信息
		String userId = eventReport.getReportUser().getId();
		Account a = accountService.getRepository().findByUserAndRoleName(userId, "游客");
		if(a != null) {
			//获取配置信息
			List<Option> option = optionService.getRepository().findByGroupAndTitle("时间周期", "游客奖励");
			if(option.size() > 0) {
				String type = option.get(0).getValue();
				String value = option.get(0).getExtended1();
				java.util.Date begin = ExdeUtil.getDateBefore(eventReport.getReportAccTime(), type, value);
				java.util.Date end = ExdeUtil.getDateEnd(eventReport.getReportAccTime());
				int sameCount = visitorRewardService.getUserSameCycleAndTypeCount(userId, eventRegister.getId(), begin, end);
				//奖励分数
				EventType eventType = eventTypeService.getRepository().findOne(eventRegister.getRegisterEventType().getId());
				double firstRewardScore = eventType.getFirstRewardScore();
				double rewardScore = eventType.getRewardScore();
				VisitorReward visitorReward = null;
				if(sameCount == 0) {//首次上报事件
					visitorReward = visitorRewardService.getRepository().findByEventRegister(eventRegister.getId());
					if(visitorReward == null) {
						visitorReward = new VisitorReward();
						visitorReward.setRegister(eventRegister);
						visitorReward.setUser(a.getUser());
						visitorReward.setRewardValue(firstRewardScore);
						visitorReward.setEventType(eventType);
						visitorReward.setGridArea(eventRegister.getRegisterEventToNetGrid());
					}else {
						visitorReward.setRewardValue(firstRewardScore);
						visitorReward.setEventType(eventType);
						visitorReward.setGridArea(eventRegister.getRegisterEventToNetGrid());
					}
					visitorRewardService.getRepository().save(visitorReward);
				}else{
					visitorReward = visitorRewardService.getRepository().findByEventRegister(eventRegister.getId());
					if(visitorReward == null) {
						visitorReward = new VisitorReward();
						visitorReward.setRegister(eventRegister);
						visitorReward.setUser(a.getUser());
						visitorReward.setRewardValue(rewardScore);
						visitorReward.setEventType(eventType);
						visitorReward.setGridArea(eventRegister.getRegisterEventToNetGrid());
					}else {
						if(!eventType.getId().equals(visitorReward.getEventType().getId()) 
								|| !eventRegister.getRegisterEventToNetGrid().getId().equals(visitorReward.getGridArea().getId())) {
							visitorReward.setRewardValue(rewardScore);
							visitorReward.setEventType(eventType);
							visitorReward.setGridArea(eventRegister.getRegisterEventToNetGrid());
							visitorRewardService.getRepository().save(visitorReward);
						}
					}
				}
			}
		}
		if(isMessageToReport){
			//短信通知上报者
			String content = "【悦来城市综合服务平台】您的案件已受理，案件编号["+eventRegister.getRegisterEventIdentify()
			+"]，将会第一时间派遣至职能部门处置，请耐心等待处置结果，感谢您的支持！";
			
			Option op = this.optionService.findByGroupAndExtended1("通知短信格式","事件受理通知");
			if (op!= null) {
				content = op.getTitle();
			}
			content=content.replace("{0}", eventRegister.getRegisterEventIdentify());
			Map<String, Object> mapTemp =this.sendMessage(eventReport.getReportUser().getContactType(), content);
			if(mapTemp.get("code")!=null&&mapTemp.get("code").equals(1)){
			//是否记录日志	
				operateLogService.log(this.getMyAccount().getUser(), "事件受理通知", content);
			}else{
				operateLogService.log(this.getMyAccount().getUser(), "事件受理通知", "发送通知受理消息失败!");
			}
			//------------
			//短信通知扣分者
			sendMsgToMarksUser(eventRegister);
			//----
		}
		if(registerState.equals("已分配")){
			this.sendMsgToDealUser(eventRegister.getRegisterEventToNetGrid(), eventRegister.getRegisterEventType().getId(),eventRegister.getRegisterEventIdentify() , eventRegister.getRegisterEventAdress());
		}
		code = 1;
		map.put("code", code);
		return map;
	}
	@RequestMapping(value = "submitEventRegister", method = RequestMethod.POST)
	public MsgHelper submitEventRegister(@RequestBody Map<String, Object> request) {
		String id =(String)request.get("id");
		String submitStr=this.eventRegisterService.submitEventRegister(id,this.getMyAccount().getUser());
		MsgHelper helper =MsgHelper.success().put("code", 1);
		helper.put("submitStr", submitStr);
		if(submitStr.contains("发布成功")){
			EventRegister eventRegister=this.eventRegisterService.getRepository().findOne(id);
			this.sendMsgToDealUser(eventRegister.getRegisterEventToNetGrid(), eventRegister.getRegisterEventType().getId(),eventRegister.getRegisterEventIdentify() , eventRegister.getRegisterEventAdress());
		}
		return helper;
	}
	
	@RequestMapping(value = "backEventRegister", method = RequestMethod.POST)
	public MsgHelper backEventRegister(@RequestBody Map<String, Object> request) {
		String id =(String)request.get("id");
		String backMemo=(String) request.get("backMemo");
		String backStr=this.eventRegisterService.backEventRegister(id,backMemo,this.getMyAccount().getUser());
		MsgHelper helper =MsgHelper.success().put("code", 1);
		helper.put("backStr", backStr);
		return helper;
	}
	
	@RequestMapping(value = "rejectEventRegister", method = RequestMethod.POST)
	public MsgHelper rejectEventRegister(@RequestBody Map<String, Object> request) {
		String id =(String)request.get("id");
		String rejectMemo=(String) request.get("rejectMemo");
		String rejectStr=this.eventRegisterService.rejectEventRegister(id,rejectMemo,this.getMyAccount().getUser(),"");
		MsgHelper helper =MsgHelper.success().put("code", 1);
		helper.put("rejectStr", rejectStr);
		return helper;
	}
	
	@RequestMapping(value = "rejectBackEventRegister", method = RequestMethod.POST)
	public MsgHelper rejectBackEventRegister(@RequestBody Map<String, Object> request) {
		String id =(String)request.get("id");
		String rejectBackMemo=(String) request.get("rejectBackMemo");
		String rejectBackStr=this.eventRegisterService.rejectBackEventRegister(id,rejectBackMemo,this.getMyAccount().getUser());
		MsgHelper helper =MsgHelper.success().put("code", 1);
		helper.put("rejectBackStr", rejectBackStr);
		return helper;
	}
	
	@RequestMapping(value = "receiveEventRegister", method = RequestMethod.POST)
	public MsgHelper receiveEventRegister(@RequestBody Map<String, Object> request) {
		String id =(String)request.get("id");
		String receiveStr=this.eventRegisterService.reveiveEventRegister(id,this.getMyAccount().getUser());
		MsgHelper helper =MsgHelper.success().put("code", 1);
		helper.put("receiveStr", receiveStr);
		return helper;
	}
	
	@RequestMapping(value = "getRejectBackReason", method = RequestMethod.GET)
	public MsgHelper getRejectBackReason() {
		String id =(String)request.getParameter("id");
		EventTask reasonStr=this.eventRegisterService.getRejectBackReason(id);
		EventRegister register = eventRegisterService.getRepository().findOne(id);
		MsgHelper helper =MsgHelper.success().put("code", 1);
		helper.put("reasonStr", reasonStr);
		helper.put("register", register);
		return helper;
	}
	@RequestMapping(value = "getRealTimeEventIdentify", method = RequestMethod.GET)
	public MsgHelper getRealTimeEventIdentify() {
		
		String eventTypeId =(String)request.getParameter("eventTypeId");
		double longitude =Double.parseDouble(request.getParameter("longitude"));
		double latitude =Double.parseDouble(request.getParameter("latitude"));
		
		GridAreaInfo info= this.gridAreaInfoService.GetGridAreaInfoByCoordinate(longitude,latitude);
		
		MsgHelper helper =MsgHelper.success().put("codeForGrid", 1);
		helper.put("gridInfo", info);
		/*if(info!=null){
			List<Grading> gradings= this.gridUserDetailsService.getRepository().getGradingByGrid(info.getId());
			helper.put("gradings", gradings);
		}*/
		
		String areaId="";
		if(info!=null&&info.getDivision()!=null){
			areaId=info.getDivision().getId();
		}
		try{
			String eventIdentify=this.identifyService.getEventIdentifyByGridAndEventType(areaId, eventTypeId);
		    helper.put("codeForEventIdentify", 1);
			helper.put("eventIdentify", eventIdentify);
			
			if(info!=null){
				helper.put("gridInfo", info);
				List<PartBaseInfo> partInfo=this.partBaseInfoService.getRepository().findByGridAreaId(info.getId());
				helper.put("partInfo", partInfo);
			}
			
			return helper;
		}catch(Exception ex){
			return helper.put("codeForEventIdentify", -1);
		}
	}
	
	@RequestMapping(value = "getGrading", method = RequestMethod.GET)
	public MsgHelper getGrading() {
		double longitude =Double.parseDouble(request.getParameter("longitude"));
		double latitude =Double.parseDouble(request.getParameter("latitude"));
		
		GridAreaInfo info= this.gridAreaInfoService.GetGridAreaInfoByCoordinate(longitude,latitude);
		
		MsgHelper helper =MsgHelper.success().put("codeForGrid", 1);
		helper.put("gridInfo", info);
		if(info!=null){
			List<Grading> gradings= this.gridUserDetailsService.getRepository().getGradingByGrid(info.getId());
			if(gradings!=null&&gradings.size()>0){
				gradings.sort((Grading g1, Grading g2) -> g1.getGradingLevel().getExtended1().compareTo(g2.getGradingLevel().getExtended1()));	
			}
			helper.put("gradings", gradings);
		}
			return helper;
	}
	
	@RequestMapping(value = "getManagmentPersonByEventTypeAndGrid", method = RequestMethod.GET)
	public Map<String, Object> getManagmentPersonByEventTypeAndGrid() {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		
		String eventTypeId =(String)request.getParameter("eventTypeId");
		double longitude =Double.parseDouble(request.getParameter("longitude"));
		double latitude =Double.parseDouble(request.getParameter("latitude"));
		
		GridAreaInfo info= this.gridAreaInfoService.GetGridAreaInfoByCoordinate(longitude,latitude);
		List<User> users=new ArrayList<>();
		int count =0;
		if(info!=null){
			String infoid=info.getId();
			 users = this.userService.getUsersByEventTypeAndGrid(start,length,eventTypeId, info.getId(),null,null);
			 count = this.userService.getUsersByEventTypeAndGridCount(eventTypeId,info.getId());
		}
		
		map.put("data", users);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 通知上报者已受理事件
	 * @param info
	 * @param eventTypeId
	 * @param identify
	 * @param adress
	 */
	private void sendMsgToDealUser(GridAreaInfo info,String eventTypeId,String identify,String adress){
		try {
			if (info != null) {
				List<User> users = this.userService.getRepository().findUsersByEventTypeAndGrid(eventTypeId,
						info.getId());
				String phoneList = "";
				if (users != null) {
					for (int i = 0; i < users.size(); i++) {
						if (users.get(i).getContactType().length() == 11) {// 手机号码
							phoneList += users.get(i).getContactType() + ",";
						}
					}
				}
				if (phoneList != "") {
					phoneList = phoneList.substring(0, phoneList.length() - 1);
					// 短信通知
					String content = "【贵阳市白云区城管局】您有新的案件到达，案件[" + identify + "]，案件位置：[" + adress
							+ "]，请登录执法端APP查看案件详情并及时处理此案件！";

					Option op = this.optionService.findByGroupAndExtended1("通知短信格式", "案件到达通知");
					if (op != null) {
						content = op.getTitle();
					}
					content = content.replace("{0}", identify);
					content = content.replace("{1}", adress);
					Map<String, Object> mapTemp = this.sendMessage(phoneList, content);
					if (mapTemp.get("code") != null && mapTemp.get("code").equals(1)) {
						// 是否记录日志
						operateLogService.log(this.getMyAccount().getUser(), "案件到达通知", content);
					} else {
						operateLogService.log(this.getMyAccount().getUser(), "案件到达通知", "发送案件到达通知失败!");
					}
					// ------------
				}
			}
		} catch (Exception ex) {

		}
		
	}
	// 获得本月第一天0点时间  
    public static Date getTimesMonthmorning() {  
        Calendar cal = Calendar.getInstance();  
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);  
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));  
        return  cal.getTime();  
    } 
    
    /**
     * 案件扣分通知
     * @param eventRegister
     */
	private void sendMsgToMarksUser(EventRegister eventRegister){
		try {
			List<EventToEvaluateUser> dlist=this.eventToEvaluateUserService.getRepository().findListByEventRegister(eventRegister.getId());
			if (dlist != null) {
				for (int i = 0; i < dlist.size(); i++) {
					String phoneList = "";
					double scaleForMonth = 0;
					if (dlist.get(i).getRegisterUser() != null) {
						phoneList = dlist.get(i).getRegisterUser().getContactType();
						scaleForMonth = this.eventToEvaluateUserService.getUserMarkScoreByDate(
								dlist.get(i).getRegisterUser().getId(), getTimesMonthmorning(),
								DateTime.now().toDate());
					}
					if (phoneList != "") {
						// 短信通知
						String content = "【悦来城市综合服务平台】案件发生，案件["
								+ dlist.get(i).getRegisterEvent().getRegisterEventIdentify() + "]已确认。根据塔型压力扣分机制，该案件扣["
								+ dlist.get(i).getScale() + "]，当月累计扣分[" + scaleForMonth + "]分。";

						Option op = this.optionService.findByGroupAndExtended1("通知短信格式", "案件扣分通知");
						if (op != null) {
							content = op.getTitle();
						}
						content = content.replace("{0}", dlist.get(i).getRegisterEvent().getRegisterEventIdentify());
						content = content.replace("{1}", Double.toString(dlist.get(i).getScale()));
						content = content.replace("{2}", Double.toString(scaleForMonth));
						Map<String, Object> mapTemp = this.sendMessage(phoneList, content);
						if (mapTemp.get("code") != null && mapTemp.get("code").equals(1)) {
							// 是否记录日志
							operateLogService.log(this.getMyAccount().getUser(), "案件扣分通知", content);
						} else {
							operateLogService.log(this.getMyAccount().getUser(), "案件扣分通知", "发送案件扣分通知失败!");
						}
						// ------------
					}
				}
			}
		} catch (Exception ex) {

		}
	}
	
	/**
	 * 获取已绑定部件层级的信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getpagebypartandgrid", method = RequestMethod.POST)
	public Map<String,Object> getPageByPartAndGrid(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		String partId = request.getParameter("partId");
		String gridId = request.getParameter("gridId");
		List<PartBaseInfo> modules=null;
		int count = 0;
		modules = partBaseInfoService.getPageByPartAndGrid(start, length, partId, gridId, key, "createTime", Sort.Direction.DESC);
		count = partBaseInfoService.getCountByPartAndGrid(partId, gridId, key);
		map.put("data", modules);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	@RequestMapping(value = "getCompletion/{eventRegisterId}", method = RequestMethod.POST)
	public Map<String,Object> getCompletion(@PathVariable("eventRegisterId") String eventRegisterId) {
		Map<String,Object> map = new HashMap<String,Object>();
		ArchiveInfo archive = archiveInfoService.getRepository().findOneArchiveByRegisterId(eventRegisterId);
		//List<EventTask> tasks = eventRegisterService.getTaskRepository().getTaskPicByEventId(eventRegisterId);
		map.put("archive", archive);
		//map.put("tasks", tasks);
		return map;
	}

	@RequestMapping(value = "getContrast/{eventRegisterId}", method = RequestMethod.POST)
	public Map<String,Object> getContrast(@PathVariable("eventRegisterId") String eventRegisterId) {
		Map<String,Object> map = new HashMap<String,Object>();
		EventRegister register = eventRegisterService.getRepository().findOne(eventRegisterId);
		List<EventTask> tasks = eventRegisterService.getTaskRepository().getTaskPicByEventId(eventRegisterId);
		map.put("register", register);
		map.put("tasks", tasks);
		return map;
	}
	
	@RequestMapping("/getProcedure/{reportId}")
	public MsgHelper getProcedure(@PathVariable("reportId") String reportId) {
		List<EventTask> procedures = eventReportService.findProcedures(reportId);
		return MsgHelper.success().put("procedures", procedures);
	}
}